#include <base/scope_exit.hpp>
#include <base/log_imp.h>
#include <base/log_output.h>
#include <base/log.h>
#include <base/Server.hpp>
#include <base/factory.hpp>
#include <log/log.h>
#include <Main/run_in_frontend.h>
#include <Main/error_signals.h>
#include <functional>
#include <thread>

namespace {


}

namespace Main {

std::function<void()> error_exit_func;

int Main() 
{
    LogOutput_Enable();
    InstallErrorSignals();
    SetScopeExitAction([] { UninstallErrorSignals(); });

    Factory<log::Log>::GetInstance().Register("logobject");
    Factory<log::Log>::GetInstance().GetObjectPtr("logobject") -> fillDefaultConfig();
    Factory<log::Log>::GetInstance().GetObjectPtr("logobject") -> initialize();

    bool error_exit_wait = false;

    LogOutput_Disable();

    error_exit_func = [&]() {
        // 保存日志
        Factory<log::Log>::GetInstance().GetObjectPtr("logobject") -> cleanup();

        while (error_exit_wait){
            std::this_thread::sleep_for(std::chrono::seconds(1));
        }
        
    };
    
    Server *server = new Server(51234);
    // 网络阻塞住，动态更改文件输出目录,以json格式传递信息进入,SIGPIPE独立处理
    if (!server->Loop()) {
        LogErr("server Loop false. Exit");
    }
    // 阻塞，接收到SIGCTL等信号处理
    delete server;

    LogInfo("Bye!");
    LogOutput_Enable();
    Factory<log::Log>::GetInstance().GetObjectPtr("logobject") -> cleanup();

    return 0;
}

void Start()
{
	std::thread t(Main);
    t.detach();
}


}